//map.js
var app = getApp();
// 引入SDK核心类
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var demo = new QQMapWX({
  key: 'OQOBZ-SP43O-F53W5-SUVB5-TUUGO-Z2BMX' // 必填
});

Page({
  data: {
    mapobj: null,
    mapOk: false, //地图显示隐藏 为了解决一些显示的bug
    scale: 14,
    // longitude: 0,
    // latitude: 0,
    // initLongitude: 0,
    // initLatitude: 0,
    //markers: [],//initMarkers 生成
    //markersData: [],//initMarkers 生成
    // markersConfig: {//暂时没用上
    //   iconPath: "/image/play.png",
    //   width: 25,
    //   height: 25
    // },
    //controls: [],//initPageStatus 生成
    loopPosition: true,
    //autoPlayOff: true//initPageStatus 生成
  },
  regionchange(e) {
    console.log(this.data.scale);
    // if( e.type == 'end'){
    //   让地图回到当前所在位置导致marker不显示的补救方法，每次移动地图都更新一下marker
    //   this.initMarkers(this.data.markersData);
    // };
  },
  //标记的事件分发
  markertap(e) {
    // 当前点击标记的状态
    var index = e.markerId;
    var nowTapAudioStatus = this.data.markersData[index].audioOff;

    if (nowTapAudioStatus) {
      //音频正在播放
      this.stopAudio(index);
    } else {
      //音频正在播放
      this.playAudio(index);
    };
  },
  //控件的事件分发
  controltap(e) {
    var that = this;
    switch (e.controlId) {
      case 1:
        // this.data.mapobj.getCenterLocation({
        //   success: function(res) {
        //     console.log(res)
        //   }
        // });
        this.setAutoPlay();
        break;
      case 2:
        this.getMyPosition();
        break;
    };
  },
  maptap: function(e) {
    console.log('点击地图', e);
  },
  //实时定位
  loopGetPosition: function() {
    if (!this.data.autoPlayOff) {
      return;
    };
    var that = this;
    wx.getLocation({
      type: 'gcj02',
      complete: function(res) {
        if( res.errMsg == 'getLocation:ok' ){
          console.log('定位成功');
          var latitude = res.latitude;
          var longitude = res.longitude;
          that.setData({
            // 实时定位不需要马上改变地图的位置
            // longitude: longitude, //把地图焦点移到景区
            // latitude: latitude,
            initLongitude: longitude,
            initLatitude: latitude
          });
          that.positionControler(latitude, longitude);
        }else{
          console.log('定位失败');
        };

        //递归循环 上次定位成功后5秒再次定位
        if (that.data.loopPosition) {
          setTimeout(function() {
            that.loopGetPosition();
          }, 5000);
        };
      }
    });
  },
  //距离集中处理判断
  positionControler: function(lat, long) {
    var that = this;
    var nowlat = lat;
    var nowlong = long;
    var scenicLists = this.data.markersData;
    var length = scenicLists.length;

    var distances = [];
    for (var i = 0; i < length; i++) {
      var json = {
        distance: this.getDistance(nowlat, nowlong, scenicLists[i].GaoDeLat, scenicLists[i].GaoDeLon),
        fromLat: nowlat,
        fromLong: nowlong,
        toLat: scenicLists[i].GaoDeLat,
        toLong: scenicLists[i].GaoDeLon,
        index: i
      };
      distances.push(json);
      // 调用计算方法，用结果进行判断
      if (json.distance <= scenicLists[i].distance) {
        console.log('范围内');
        that.playAudio(i);
      } else {
        console.log('范围外');
      };
    };
  },
  //自动播放控制
  setAutoPlay: function() {
    if (this.data.autoPlayOff) {
      //正在自动播放
      this.data.controls[0].iconPath = '/image/play.png';
      this.setData({
        autoPlayOff: !this.data.autoPlayOff,
        controls: this.data.controls
      });
    } else {
      //没有自动播放
      this.data.controls[0].iconPath = '/image/play1.gif';
      this.setData({
        autoPlayOff: !this.data.autoPlayOff,
        controls: this.data.controls
      });

      this.loopGetPosition();
    };
  },
  //距离计算
  getDistance: function() {
    var t = Math.sin,
      n = Math.cos,
      r = Math.sqrt,
      a = Math.asin;
    return function(fromLat, fromLong, toLat, toLong) {
      var s = 12742001.5798544,
        i = .01745329251994329;
      var e = fromLat * i,
        f = fromLong * i,
        o = toLat * i,
        v = toLong * i,
        q = t(e),
        b = t(f),
        d = n(e),
        g = n(f),
        j = t(o),
        k = t(v),
        l = n(o),
        m = n(v),
        p = d * g,
        w = d * b,
        x = l * m,
        y = l * k,
        z = r((p - x) * (p - x) + (w - y) * (w - y) + (q - j) * (q - j));
      return a(z / 2) * s;
    };
  }(),
  //回到当前地址
  getMyPosition: function() {
    this.setData({
      mapOk: false
    });
    this.setData({
      longitude: this.data.initLongitude,
      latitude: this.data.initLatitude,
      scale: 14
    });
    this.setData({
      mapOk: true
    });
    // 用提供的接口 让地图回到当前所在位置，但是有BUG可能导致marker不显示
    // this.data.mapobj.moveToLocation();
  },
  //初始化数据
  initData: function() {
    //测试数据
    this.setData({
      markersData: [{
        iconPath: "/image/play.png",
        id: 0,
        Name: "测试地址",
        VoiceUrl: "http://zhangmenshiting.baidu.com/data2/music/62dc0794ca86b6515a74fec68a5f2e9f/540999926/540999926.mp3?xcode=8974e038d51dab8438b319dd5c3c046e",
        GaoDeLat: 39.90403,
        GaoDeLon: 116.407526,
        width: 50,
        height: 50
      }, {
        "Name": "王仙岭旅游风景区",
        "Code": "001",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041680528514.mp3",
        "SSid": 30305,
        "GaoDeLon": 113.08217,
        "GaoDeLat": 25.768819,
        "BaiDuLon": 113.088697,
        "BaiDuLat": 25.774613,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "",
        "Distance": 0,
        "SpaceCode": "ws86t5pf",
        "AcquTime": ""
      }, {
        "Name": "王仙岭瀑布、蝴蝶瀑布",
        "Code": "002",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041685820120.mp3",
        "SSid": 30306,
        "GaoDeLon": '0.00000',
        "GaoDeLat": '0.00000',
        "BaiDuLon": 0,
        "BaiDuLat": 0,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "0",
        "Distance": 0,
        "SpaceCode": "7zzzzygm",
        "AcquTime": ""
      }, {
        "Name": "王仙庙",
        "Code": "003",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041692726781.mp3",
        "SSid": 30307,
        "GaoDeLon": 113.085312,
        "GaoDeLat": 25.769474,
        "BaiDuLon": 116.16776,
        "BaiDuLat": 28.08239,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "",
        "Distance": 20,
        "SpaceCode": "wsfxer44",
        "AcquTime": ""
      }, {
        "Name": "百凤瀑布、叠翠瀑布",
        "Code": "004",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041695744595.mp3",
        "SSid": 30308,
        "GaoDeLon": '0.00000',
        "GaoDeLat": '0.00000',
        "BaiDuLon": 0,
        "BaiDuLat": 0,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "0",
        "Distance": 0,
        "SpaceCode": "7zzzzygm",
        "AcquTime": ""
      }, {
        "Name": "绝对廊",
        "Code": "005",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041697866859.mp3",
        "SSid": 30309,
        "GaoDeLon": 113.089251,
        "GaoDeLat": 25.768138,
        "BaiDuLon": 117.562949,
        "BaiDuLat": 32.86473,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "",
        "Distance": 5,
        "SpaceCode": "wtgdgjcc",
        "AcquTime": ""
      }, {
        "Name": "露泉、樱花园",
        "Code": "006",
        "VoiceUrl": "https://yjly.oss-cn-beijing.aliyuncs.com/yjly/voice/144041700944898.mp3",
        "SSid": 30310,
        "GaoDeLon": '0.00000',
        "GaoDeLat": '0.00000',
        "BaiDuLon": 0,
        "BaiDuLat": 0,
        "GoogLeLon": 0,
        "GoogLeLat": 0,
        "Altitude": "0",
        "Distance": 0,
        "SpaceCode": "7zzzzygm",
        "AcquTime": ""
      }]
    });
    //添加景点播放范围
    for (var i = 0; i < this.data.markersData.length; i++) {
      this.data.markersData[i].distance = 90000;
    };
    this.setData({
      markersData: this.data.markersData
    });
  },
  //初始化一些状态
  initPageStatus: function(w,h){
    var that = this;
    //根据定位是否成功  确定自动播放状态 开启自动播放 关闭自动播放 无法自动播放
    wx.getLocation({
      success: function(res) {
        //这里需要再次考虑 定位失败的坐标放在哪里
        that.setData({
          longitude: 113.08217, //把地图焦点移到景区
          latitude: 25.768819,
          initLongitude: res.longitude,
          initLatitude: res.latitude,
          mapOk: true, //判断map 的显示和隐藏
          autoPlayOff: true,
          //初始化固定控件
          controls: [{
            id: 1,
            iconPath: '/image/play1.gif',
            position: {
              left: 20,
              top: 20,
              width: 50,
              height: 50
            }
          }, {
            id: 2,
            iconPath: '/image/1.png',
            position: {
              left: w - 50 - 20,
              top: h - 50 - 20,
              width: 50,
              height: 50
            }
          }]
        });
        //开启实时定位
        that.data.loopPosition = true;
        that.loopGetPosition();
      },
      fail: function(res) {
        //这里需要再次考虑 定位失败的坐标放在哪里
        that.setData({
          longitude: 113.08217, //把地图焦点移到景区
          latitude: 25.768819,
          initLongitude: res.longitude,
          initLatitude: res.latitude,
          mapOk: true, //判断map 的显示和隐藏
          autoPlayOff: false,
          //初始化固定控件
          controls: [{
            id: 2,
            iconPath: '/image/1.png',
            position: {
              left: w - 50 - 20,
              top: h - 50 - 20,
              width: 50,
              height: 50
            }
          }]
        });
        //清空实时定位功能
        that.data.loopPosition = false;
        that.loopGetPosition = function() {};

        wx.showModal({
          title: "定位失败",
          content: "请检查网络后重新打开",
          showCancel: false,
          success: function(res){
            console.log(res);
          }
        });
      }
    });    
  },
  //初始化标记位置
  initMarkers: function() {
    var markersData = this.data.markersData;
    var markers = [];
    for (var i = 0; i < markersData.length; i++) {
      //添加播放状态字段 false 为未播放 true 为播放
      markersData[i].audioOff = false;

      var marke = {
        id: i,
        label: {
          content: markersData[i].Name
        },
        iconPath: "/image/play.png",
        width: 25,
        height: 25,
        latitude: markersData[i].GaoDeLat,
        longitude: markersData[i].GaoDeLon,
      };
      markers.push(marke);
    };

    // 当前是否正在播放
    var audio = app.globalData.audioConsole;
    var audioSrc = audio.src;
    var nowAudioIndex = audio.mapAudioIndex;
    //audio含有 mapAudioIndex 且是数字 src 地址也一致才能判断播放的是本页音频
    if (nowAudioIndex && !isNaN(nowAudioIndex) && audioSrc == markersData[nowAudioIndex].VoiceUrl) {
      markersData[nowAudioIndex].audioOff = true;
      markers[nowAudioIndex].iconPath = "/image/play1.gif"
    } else {
      audio.mapAudioIndex = '';
    };

    this.setData({
      markersData: markersData,
      markers: markers
    });
  },
  //初始化audio 自然播放完毕后的回调
  initAudioCallBack: function() {
    var that = this;
    app.audioEndCallback = function() {
      var index = app.globalData.audioConsole.mapAudioIndex;
      that.stopAudio(index);
    };
  },
  clearAudioCallBack: function() {
    app.audioEndCallback = function() {};
  },
  playAudio: function(index) {
    var lengths = this.data.markers.length;
    for (var i = 0; i < lengths; i++) {
      this.data.markers[i].iconPath = "/image/play.png";
      this.data.markersData[i].audioOff = false;
    };
    this.data.markers[index].iconPath = "/image/play1.gif";
    this.data.markersData[index].audioOff = true;
    this.setData({
      markers: this.data.markers,
      markersData: this.data.markersData
    });

    // 设置了 src 之后会自动播放
    app.globalData.audioConsole.src = this.data.markersData[index].VoiceUrl;
    app.globalData.audioConsole.title = this.data.markersData[index].Name;
    app.globalData.audioConsole.mapAudioIndex = index; //用于标记当前播放了哪个音频
  },
  stopAudio: function(index) {
    var lengths = this.data.markers.length;
    for (var i = 0; i < lengths; i++) {
      this.data.markers[i].iconPath = "/image/play.png";
      this.data.markersData[i].audioOff = false;
    };
    this.setData({
      markers: this.data.markers,
      markersData: this.data.markersData
    });

    app.globalData.audioConsole.mapAudioIndex = ''; //播放赋值，停止清空
    app.globalData.audioConsole.stop();
  },
  onLoad: function() {
    var that = this;
    // 初始化数据
    this.initData();
    // 重新获取窗口信息尺寸（安卓上，初始化获取的可能不准确）
    wx.getSystemInfo({
      success: function(data) {
        that.setData({
          winWidth: data.windowWidth,
          winHeight: data.windowHeight,
          mapobj: wx.createMapContext('map')
        });
      }
    });
    // 初始化音频回调函数
    this.initAudioCallBack();
    // 初始化标记
    this.initMarkers();

    // 初始化页面的一些状态
    // 获取当前定位 并且显示地图
    // 初始化固定控件
    this.initPageStatus(this.data.winWidth, this.data.winHeight);
  },
  onUnload: function() {
    this.clearAudioCallBack();

    this.data.loopPosition = false;
    this.loopGetPosition = function() {};

    app.globalData.audioConsole.stop();
  }
})